package com.train.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.user.domain.UserPlan;
import com.train.user.domain.UserPlanItem;
import com.train.user.mapper.UserPlanMapper;
import com.train.user.mapper.UserPlanItemMapper;
import com.train.user.service.UserPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.train.common.constant.HttpStatus;

/**
* @author HP
* @description 针对表【user_plan(用户计划表)】的数据库操作Service实现
* @createDate 2025-11-04 17:48:26
*/
@Service
public class UserPlanServiceImpl extends ServiceImpl<UserPlanMapper, UserPlan> implements UserPlanService {

    @Autowired
    private UserPlanItemMapper userPlanItemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserPlan createPlan(Long userId, String planName, String planType) {
        // 检查计划名称是否已存在
        LambdaQueryWrapper<UserPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPlan::getUserId, userId)
                .eq(UserPlan::getPlanName, planName);
        if (baseMapper.exists(queryWrapper)) {
            throw new RuntimeException("该计划名称已存在");
        }

        // 创建新计划
        UserPlan userPlan = new UserPlan();
        userPlan.setUserId(userId);
        userPlan.setPlanName(planName);
        userPlan.setPlanType(planType);
        userPlan.setTotalDuration(0);
        userPlan.setCompletedDuration(0);
        userPlan.setStatus("0"); // 默认进行中
        userPlan.setCreateTime(new Date());
        userPlan.setUpdateTime(new Date());

        if (!save(userPlan)) {
            throw new RuntimeException("创建失败");
        }

        return userPlan;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserPlan updatePlan(Long userId, Long planId, String planName, String status) {
        // 验证计划所有权
        UserPlan userPlan = validatePlanOwnership(userId, planId);
        if (userPlan == null) {
            throw new RuntimeException("计划不存在或无权限");
        }

        // 更新计划名称
        if (planName != null && !planName.equals(userPlan.getPlanName())) {
            // 检查新名称是否已存在
            LambdaQueryWrapper<UserPlan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserPlan::getUserId, userId)
                    .eq(UserPlan::getPlanName, planName)
                    .ne(UserPlan::getPlanId, planId);
            if (baseMapper.exists(queryWrapper)) {
                throw new RuntimeException("该计划名称已存在");
            }
            userPlan.setPlanName(planName);
        }

        // 更新状态，确保状态是整数类型
        if (status != null) {
            try {
                userPlan.setStatus(String.valueOf(Integer.parseInt(status)));
            } catch (NumberFormatException e) {
                throw new RuntimeException("状态值格式错误");
            }
        }

        userPlan.setUpdateTime(new Date());
        if (!updateById(userPlan)) {
            throw new RuntimeException("更新失败");
        }

        return userPlan;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePlan(Long userId, Long planId) {
        // 验证计划所有权
        UserPlan userPlan = validatePlanOwnership(userId, planId);
        if (userPlan == null) {
            throw new RuntimeException("计划不存在或无权限");
        }

        // 级联删除计划项目
        LambdaQueryWrapper<UserPlanItem> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(UserPlanItem::getPlanId, planId);
        userPlanItemMapper.delete(itemQueryWrapper);

        // 删除计划
        if (!removeById(planId)) {
            throw new RuntimeException("删除失败");
        }
    }

    /**
     * 获取用户计划列表
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param planType 计划类型
     * @param status 状态
     * @return 计划列表
     */
    @Override
    public List<UserPlan> getUserPlans(Long userId, Integer pageNum, Integer pageSize, String planType, String status) {
        LambdaQueryWrapper<UserPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPlan::getUserId, userId);
        
        // 计划类型筛选
        if (planType != null && !planType.isEmpty()) {
            try {
                queryWrapper.eq(UserPlan::getPlanType, Integer.parseInt(planType));
            } catch (NumberFormatException e) {
                throw new RuntimeException("计划类型格式错误");
            }
        }
        
        // 状态筛选
        if (status != null && !status.isEmpty()) {
            try {
                queryWrapper.eq(UserPlan::getStatus, Integer.parseInt(status));
            } catch (NumberFormatException e) {
                throw new RuntimeException("状态值格式错误");
            }
        }
        
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(UserPlan::getCreateTime);
        
        // 执行分页查询
        Page<UserPlan> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);
        
        return page.getRecords();
    }

    @Override
    public Map<String, Object> getPlanDetail(Long userId, Long planId) {
        // 验证计划所有权
        UserPlan userPlan = validatePlanOwnership(userId, planId);
        if (userPlan == null) {
            throw new RuntimeException("计划不存在或无权限");
        }
        
        // 构建计划详情
        Map<String, Object> result = new HashMap<>();
        result.put("planId", userPlan.getPlanId());
        result.put("planName", userPlan.getPlanName());
        result.put("planType", userPlan.getPlanType());
        result.put("totalDuration", userPlan.getTotalDuration());
        result.put("completedDuration", userPlan.getCompletedDuration());
        result.put("status", userPlan.getStatus());
        result.put("createTime", userPlan.getCreateTime());
        result.put("updateTime", userPlan.getUpdateTime());
        
        // 计算进度百分比
        int progressRate = 0;
        if (userPlan.getTotalDuration() > 0) {
            progressRate = (int) (userPlan.getCompletedDuration() * 100.0 / userPlan.getTotalDuration());
        }
        result.put("progressRate", progressRate);
        
        // 获取计划项目列表
        LambdaQueryWrapper<UserPlanItem> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(UserPlanItem::getPlanId, planId)
                .orderByAsc(UserPlanItem::getSort);
        List<UserPlanItem> items = userPlanItemMapper.selectList(itemQueryWrapper);
        
        // 转换项目列表为响应格式
        List<Map<String, Object>> itemList = new ArrayList<>();
        for (UserPlanItem item : items) {
            Map<String, Object> itemMap = new HashMap<>();
            itemMap.put("itemId", item.getItemId());
            itemMap.put("itemType", item.getItemType());
            itemMap.put("itemIdRef", item.getItemIdRef());
            itemMap.put("itemDuration", item.getItemDuration());
            itemMap.put("completedDuration", item.getCompletedDuration());
            
            // 计算项目进度百分比
            int itemProgress = 0;
            if (item.getItemDuration() > 0) {
                itemProgress = (int) (item.getCompletedDuration() * 100.0 / item.getItemDuration());
            }
            itemMap.put("itemProgress", itemProgress);
            
            // 这里需要根据itemIdRef查询课程或视频集的名称
            // 暂时设置为默认值，实际实现时需要调用相应的服务
            itemMap.put("itemName", "项目名称" + item.getItemIdRef());
            
            itemList.add(itemMap);
        }
        
        result.put("items", itemList);
        
        return result;
    }

    @Override
    public UserPlan validatePlanOwnership(Long userId, Long planId) {
        LambdaQueryWrapper<UserPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPlan::getPlanId, planId)
                .eq(UserPlan::getUserId, userId);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePlanDuration(Long planId) {
        // 查询计划下所有项目
        LambdaQueryWrapper<UserPlanItem> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(UserPlanItem::getPlanId, planId);
        List<UserPlanItem> items = userPlanItemMapper.selectList(itemQueryWrapper);

        // 计算总时长和完成时长
        int totalDuration = 0;
        int completedDuration = 0;
        for (UserPlanItem item : items) {
            if (item.getItemDuration() != null) {
                totalDuration += item.getItemDuration();
            }
            if (item.getCompletedDuration() != null) {
                completedDuration += item.getCompletedDuration();
            }
        }

        // 更新计划的总时长和完成时长
        UserPlan userPlan = getById(planId);
        if (userPlan != null) {
            userPlan.setTotalDuration(totalDuration);
            userPlan.setCompletedDuration(completedDuration);
            userPlan.setUpdateTime(new Date());
            updateById(userPlan);
        }
    }
}




